/**
 * 行结构数据转化为树形结构数据
 * @param {*} rows 
 * @param {*} config {
              id: 'id',// id字段
              pid: 'pid',// 上级id字段
              children: 'subNode',// 生成的下级节点key字段
              rootKey: '0' // 根节点上级id
            }
 * @returns 
 */
const rowData2TreeData = (rows, config) => {
  const keyNodes = {},
    parentKeyNodes = {};
  for (let i = 0; i < rows.length; i++) {
    let row = rows[i]; // 将行数据整体赋值后再做需要的处理
    row.id = row[config.id];
    row[config.pid] = row[config.pid];
    row[config.children] = [];

    keyNodes[row.id] = row;

    if (parentKeyNodes[row[config.pid]]) {
      parentKeyNodes[row[config.pid]].push(row);
    } else {
      parentKeyNodes[row[config.pid]] = [row];
    }

    let children = parentKeyNodes[row.id];
    if (children) {
      row[config.children] = children;
    }

    let pNode = keyNodes[row[config.pid]];
    if (pNode) {
      pNode[config.children].push(row);
    }
  }
  return parentKeyNodes[config.rootKey];
};

/* 获取url中参数 */
const getQueryVariable = (variable) => {
  // url解码中文字符
  let query = decodeURIComponent(window.location.href.substring(1));
  let vars = [];
  if (query.indexOf("?") > -1) {
    query = query.split("?")[1];
    if (query.indexOf("&") > -1) {
      vars = query.split("&");
    } else {
      vars.push(query);
    }
  } else {
    return ""
  }
  // if (query.indexOf("&") > -1) {
  //   vars = query.split("&");
  // } else {
  //   vars = query.split("?");
  // }
  for (let i = 0; i < vars.length; i++) {
    let pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return "";
}


// 简化版的list转树形，需要字段名严格为 value , pvalue 
// root 参数为根节点 value
const listToTree = (list, root) => {
  let map = {};
  list.forEach(item => {
    if (!map[item.value]) {
      map[item.value] = item;
    }
  });

  list.forEach(item => {
    if (item.pvalue !== root) {
      if (map[item.pvalue].children) {
        map[item.pvalue].children.push(item)
      } else {
        map[item.pvalue]['children'] = [item]
      }
    }
  });

  return list.filter(item => {
    if (item.pvalue === root) {
      return item;
    }
  })
}


const formatJson = (filterVal, jsonData) => {
  return jsonData.map(v => filterVal.map(j => v[j]))
}



export {
  rowData2TreeData,
  getQueryVariable,
  listToTree
};